<template>
  <el-dialog :close-on-click-modal="false" title="修改信息" width="800px" :visible.sync="visible">
    <el-form ref="form" :model="form" label-width="80px" :rules="rules">
      <el-form-item label="姓名" prop="name">
        <el-input
          type="text"
          allowClear
          autocomplete="false"
          placeholder="请输入姓名"
          v-model="form.name"
        />
      </el-form-item>
      <el-form-item v-show="false" label="用户ID">
        <el-input type="text" :disabled="false" v-model="form.userId" />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input
          type="text"
          allowClear
          autocomplete="false"
          placeholder="请输入用户名"
          v-model="form.username"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          type="text"
          clearable
          autocomplete="false"
          placeholder="请输入手机号"
          v-model.number="form.phone"
        />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button @click="handleOk" type="primary">修改</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateUserInfo } from '@/api/department'
import { openNotification, isvalidPhone } from '@/utils/util'
import pick from 'lodash.pick'

export default {
  data() {
    const validPhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if (!isvalidPhone(value)) {
        callback(new Error('请输入正确的11位手机号码'))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      form: {
        userId: null,
        name: null,
        phone: null
      },
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        phone: [{ required: true, validator: validPhone, trigger: 'blur' }]
      }
    }
  },
  methods: {
    handleOk(e) {
      e.stopPropagation()
      this.$refs.form.validate(async valid => {
        if (valid) {
          const res = await updateUserInfo(this.form)
          console.log('update res', res)
          openNotification('success', '更新操作成功')
          this.visible = false
          this.$emit('refresh')
        }
      })
    },
    edit(row) {
      console.log('row', row)
      this.form = Object.assign({}, row)
      this.visible = true
    }
  }
}
</script>
